package com.har.modules.business.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.har.common.utils.R;
import com.har.utils.security.Base64Util;
import com.har.utils.string.CheckUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author macwy
 * @Title:har-balance-web
 * @Package com.har.controller
 * @Description 导出数据
 * @date 2018/3/23 10:40
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/export",produces = "application/json")
public class ExportController {

    /**
     * 检测文件是否生成
     * @param param
     * @return
     */
    @RequestMapping("/checkFile")
    public R checkFile(@RequestBody String param){
        JSONObject dataJson = JSON.parseObject(param);
        if(CheckUtil.isNull(dataJson.getString("filePath"))){
            return  R.error("参数有误");
        }
        String filePath = dataJson.getString("filePath");
        filePath = Base64Util.decodeBase64(filePath);

        File file =new File(filePath);
        //如果文件夹不存在则创建
        if (file.exists()) {
            return   R.ok().put("filePath",Base64Util.encodeBase64(filePath));
        } else {
            return R.error(9999,"文件生成中");
        }
    }

    /**
     * 导出
     * @param filePath
     * @param response
     */
    @RequestMapping("/file")
    public void  export(String filePath, HttpServletResponse response) throws  Exception{

        filePath = Base64Util.decodeBase64(filePath);
        File file = new File(filePath);

        response.setContentType("application/x-xls");
        response.setHeader("Content-Disposition", "attachment;filename="+filePath.substring(filePath.lastIndexOf("/")+1,filePath.length()));
        response.setContentLength((int) file.length());
        OutputStream out = null;
        FileInputStream inStream = null;
        try {
            out  = response.getOutputStream();

            inStream = new FileInputStream(file);

            int byteRead;
            byte[] buffer = new byte[1024];
            while ((byteRead = inStream.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
                out.flush();
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != out) {
                out.close();
            }
            if(null != inStream) {
                inStream.close();
            }
        }
    }
}
